<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>环境监控系统</title>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: #f5f5f5; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
        .nav { margin: 20px 0; }
        .nav button { margin-right: 10px; padding: 10px 20px; cursor: pointer; }
        .content { border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; }
        input, select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        button { background: #007bff; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .login-form { max-width: 300px; margin: 100px auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>环境监控系统</h1>
        <div id="userInfo" style="display:none;">
            欢迎, <span id="username"></span> | <button onclick="logout()">退出登录</button>
        </div>
        <div id="loginSection">
            <div class="login-form">
                <h3>用户登录</h3>
                <div class="form-group">
                    <label>用户名:</label>
                    <input type="text" id="loginUsername" value="admin">
                </div>
                <div class="form-group">
                    <label>密码:</label>
                    <input type="password" id="loginPassword" value="admin123">
                </div>
                <button onclick="login()">登录</button>
            </div>
        </div>
    </div>

    <div id="mainContent" style="display:none;">
        <div class="nav">
            <button onclick="showDevices()">设备管理</button>
            <button onclick="showEnvironmentData()">环境数据</button>
            <button onclick="showAddDevice()">添加设备</button>
            <button onclick="showRecordData()">记录数据</button>
        </div>

        <div class="content" id="contentArea">
            <!-- 动态内容区域 -->
        </div>
    </div>
</div>

<script>
    axios.defaults.baseURL = 'http://localhost:8081/environment-monitor/';
    // 登录功能
     async function login() {
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;

        try {
            const response = await fetch('./api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });

            const result = await response.json();

            if (result.success) {
                document.getElementById('loginSection').style.display = 'none';
                document.getElementById('mainContent').style.display = 'block';
                document.getElementById('userInfo').style.display = 'block';
                document.getElementById('username').textContent = result.data.username;
                await showDevices();
            } else {
                alert('登录失败: ' + result.message);
            }
        } catch (error) {
            console.error('Login error:', error);
            alert('登录失败');
        }
    }

    // 退出登录
    async function logout() {
        try {
            await fetch('/environment-monitor/api/auth/logout', { method: 'DELETE' });
            document.getElementById('loginSection').style.display = 'block';
            document.getElementById('mainContent').style.display = 'none';
            document.getElementById('userInfo').style.display = 'none';
        } catch (error) {
            console.error('Logout error:', error);
        }
    }

    // 显示设备列表
    async function showDevices() {
        try {
            const response = await fetch('./api/devices/findAll', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            console.log('Response status:', response.status);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('API Response:', result);

            if (response.ok) {
                const devices = result;
                console.log(result.length);
                let html = `
                <h3>设备列表</h3>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>设备ID</th>
                                <th>名称</th>
                                <th>类型</th>
                                <th>位置</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

                if (devices && devices.length > 0) {
                    devices.forEach(function(device) {
                        console.log('处理设备:', device);

                        html += '<tr>' +
                            '<td>' + (device.id || 'N/A') + '</td>' +
                            '<td>' + (device.deviceId || 'N/A') + '</td>' +
                            '<td>' + (device.name || 'N/A') + '</td>' +
                            '<td>' + (device.type || 'N/A') + '</td>' +
                            '<td>' + (device.location || 'N/A') + '</td>' +
                            '<td>' +
                            '<span class="status ' + (device.status ? 'active' : 'inactive') + '">' +
                            (device.status ? '正常' : '关闭') +
                            '</span>' +
                            '</td>' +
                            '<td>' + (device.createTime ? formatDateTime(device.createTime) : 'N/A') + '</td>' +
                            '<td class="actions">' +
                            '<button class="btn-edit" onclick="showEditDeviceForm(' + device.id + ')">编辑</button>' +
                            '<button class="btn-delete" onclick="deleteDevice(' + device.id + ')">删除</button>' +
                            '</td>' +
                            '</tr>';
                    });
                } else {
                    html += `
                    <tr>
                        <td colspan="8" style="text-align: center; color: #666;">
                            暂无设备数据
                        </td>
                    </tr>
                `;
                }

                html += `
                        </tbody>
                    </table>
                </div>
            `;

                document.getElementById('contentArea').innerHTML = html;
            } else {
                document.getElementById('contentArea').innerHTML = `
                <div class="error-message">
                    <h3>获取设备列表失败</h3>
                    <p>\\${result.message || '未知错误'}</p>
                </div>
            `;
            }
        } catch (error) {
            console.error('Error fetching devices:', error);
            document.getElementById('contentArea').innerHTML = `
            <div class="error-message">
                <h3>请求失败</h3>
                <p>\\${error.message}</p>
                <p>请检查网络连接或联系管理员</p>
            </div>
        `;
        }
    }

    // 日期时间格式化函数
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return 'N/A';

        try {
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        } catch (e) {
            return dateTimeStr;
        }
    }

    // 显示环境数据
    async function showEnvironmentData() {
        try {
            const response = await fetch('./api/environment-data/findAll', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            const result = await response.json();

            if (response.ok) {
                const data = result;
                let html = '<h3>环境数据</h3><table><tr><th>ID</th><th>温度</th><th>湿度</th><th>能耗</th><th>位置</th><th>时间</th></tr>';

                data.forEach(item => {
                    html += '<tr>' +
                            '<td>' + (item.id) + '</td>' +
                    '<td>' + (item.temperature) + '°C</td>' +
                    '<td>' + (item.humidity) + '%</td>' +
                    '<td>' + (item.energyConsumption) + 'kWh</td>' +
                    '<td>' + (item.location) + '</td>' +
                    '<td>' + ((item.recordedAt ? formatDateTime(item.recordedAt) : 'N/A')) + '</td>' +
                        '</tr>';
                });

                html += '</table>';
                document.getElementById('contentArea').innerHTML = html;
            }
        } catch (error) {
            console.error('Error fetching environment data:', error);
        }
    }

    // 其他功能实现...

    // 显示添加设备表单
    function showAddDevice() {
        const html = '<h3>添加新设备</h3>' +
            '<div class="form-container">' +
            '<form id="addDeviceForm" onsubmit="return false;">' +
            '<div class="form-group">' +
            '<label for="deviceName">设备名称:</label>' +
            '<input type="text" id="deviceName" name="name" required placeholder="请输入设备名称">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="deviceType">设备类型:</label>' +
            '<select id="deviceType" name="type" required>' +
            '<option value="">请选择类型</option>' +
            '<option value="AIR_CONDITIONER">空调</option>' +
            '<option value="ELECTRIC_METER">电表</option>' +
            '<option value="TEMPERATURE_SENSOR">温度传感器</option>' +
            '<option value="HUMIDITY_SENSOR">湿度传感器</option>' +
            '<option value="LIGHT_CONTROLLER">灯光控制器</option>' +
            '</select>' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="deviceLocation">位置:</label>' +
            '<input type="text" id="deviceLocation" name="location" required placeholder="请输入设备位置">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="deviceId">设备ID:</label>' +
            '<input type="text" id="deviceId" name="deviceId" required placeholder="请输入唯一设备ID">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="deviceStatus">状态:</label>' +
            '<select id="deviceStatus" name="status">' +
            '<option value="true">正常</option>' +
            '<option value="false">关闭</option>' +
            '</select>' +
            '</div>' +
            '<div class="form-actions">' +
            '<button type="button" onclick="submitDeviceForm()" style="background: #28a745;">添加设备</button>' +
            '<button type="button" onclick="showDevices()" style="background: #6c757d; margin-left: 10px;">取消</button>' +
            '</div>' +
            '</form>' +
            '</div>';

        document.getElementById('contentArea').innerHTML = html;
    }

    // 提交设备表单
    async function submitDeviceForm() {
        const deviceName = document.getElementById('deviceName').value.trim();
        const deviceType = document.getElementById('deviceType').value;
        const deviceLocation = document.getElementById('deviceLocation').value.trim();
        const deviceId = document.getElementById('deviceId').value.trim();
        const deviceStatus = document.getElementById('deviceStatus').value === 'true';

        console.log('表单数据:', {
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        });

        const formData = {
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        };

        // 简单验证
        if (!formData.name || !formData.type || !formData.location || !formData.deviceId) {
            alert('请填写所有必填字段！');
            return;
        }

        axios.post(`/api/devices/save`, {
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        }).then(async res => {
            alert('设备添加成功！');
            await showDevices(); // 返回设备列表
        }).catch(err => {
            console.error('添加设备错误:', error);
            alert('添加设备失败，请检查网络连接');
        })
    }

    // 显示记录环境数据表单
    function showRecordData() {
        const html = '<h3>记录环境数据</h3>' +
            '<div class="form-container">' +
            '<form id="recordDataForm" onsubmit="return false;">' +
            '<div class="form-group">' +
            '<label for="dataLocation">位置:</label>' +
            '<input type="text" id="dataLocation" name="location" required placeholder="请输入数据记录位置">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="dataTemperature">温度 (°C):</label>' +
            '<input type="number" id="dataTemperature" name="temperature" step="0.1" placeholder="请输入温度值">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="dataHumidity">湿度 (%):</label>' +
            '<input type="number" id="dataHumidity" name="humidity" step="0.1" min="0" max="100" placeholder="请输入湿度值">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="dataEnergy">能耗 (kWh):</label>' +
            '<input type="number" id="dataEnergy" name="energyConsumption" step="0.01" min="0" placeholder="请输入能耗值">' +
            '</div>' +
            '<div class="form-actions">' +
            '<button type="button" onclick="submitEnvironmentData()" style="background: #17a2b8;">记录数据</button>' +
            '<button type="button" onclick="showEnvironmentData()" style="background: #6c757d; margin-left: 10px;">取消</button>' +
            '</div>' +
            '</form>' +
            '</div>' +
            '<div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">' +
            '<h4>数据说明:</h4>' +
            '<ul>' +
            '<li>温度: 摄氏度 (°C)</li>' +
            '<li>湿度: 百分比 (%)，范围 0-100</li>' +
            '<li>能耗: 千瓦时 (kWh)</li>' +
            '<li>位置: 数据记录的具体位置</li>' +
            '</ul>' +
            '</div>';

        document.getElementById('contentArea').innerHTML = html;
    }

    // 提交环境数据
    async function submitEnvironmentData() {
        const formData = {
            location: document.getElementById('dataLocation').value,
            temperature: document.getElementById('dataTemperature').value ?
                parseFloat(document.getElementById('dataTemperature').value) : null,
            humidity: document.getElementById('dataHumidity').value ?
                parseFloat(document.getElementById('dataHumidity').value) : null,
            energyConsumption: document.getElementById('dataEnergy').value ?
                parseFloat(document.getElementById('dataEnergy').value) : null
        };

        // 简单验证
        if (!formData.location) {
            alert('请填写位置信息！');
            return;
        }

        axios.post(`/api/environment-data/save`, {
            location: document.getElementById('dataLocation').value,
            temperature: document.getElementById('dataTemperature').value ?
                parseFloat(document.getElementById('dataTemperature').value) : null,
            humidity: document.getElementById('dataHumidity').value ?
                parseFloat(document.getElementById('dataHumidity').value) : null,
            energyConsumption: document.getElementById('dataEnergy').value ?
                parseFloat(document.getElementById('dataEnergy').value) : null
        }).then(res => {
            alert('环境数据记录成功！');
            showEnvironmentData(); // 返回环境数据列表
        }).catch(err => {
            console.error('记录环境数据错误:', error);
            alert('记录环境数据失败，请检查网络连接');
        })
    }

    // 显示编辑设备表单
    function showEditDeviceForm(device) {
        console.log('显示编辑表单，设备:', device);

        const html = '<h3>编辑设备</h3>' +
            '<div class="form-container">' +
            '<form id="editDeviceForm" onsubmit="return false;">' +
            '<input type="hidden" id="editDeviceId" value="' + device + '">' +
            '<div class="form-group">' +
            '<label for="editDeviceName">设备名称:</label>' +
            '<input type="text" id="editDeviceName" name="name" value="' + (device.name || '') + '" required placeholder="请输入设备名称">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="editDeviceType">设备类型:</label>' +
            '<select id="editDeviceType" name="type" required>' +
            '<option value="">请选择类型</option>' +
            '<option value="AIR_CONDITIONER"' + (device.type === 'AIR_CONDITIONER' ? ' selected' : '') + '>空调</option>' +
            '<option value="ELECTRIC_METER"' + (device.type === 'ELECTRIC_METER' ? ' selected' : '') + '>电表</option>' +
            '<option value="TEMPERATURE_SENSOR"' + (device.type === 'TEMPERATURE_SENSOR' ? ' selected' : '') + '>温度传感器</option>' +
            '<option value="HUMIDITY_SENSOR"' + (device.type === 'HUMIDITY_SENSOR' ? ' selected' : '') + '>湿度传感器</option>' +
            '<option value="LIGHT_CONTROLLER"' + (device.type === 'LIGHT_CONTROLLER' ? ' selected' : '') + '>灯光控制器</option>' +
            '</select>' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="editDeviceLocation">位置:</label>' +
            '<input type="text" id="editDeviceLocation" name="location" value="' + (device.location || '') + '" required placeholder="请输入设备位置">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="editDeviceDeviceId">设备ID:</label>' +
            '<input type="text" id="editDeviceDeviceId" name="deviceId" value="' + ('') + '" required placeholder="请输入唯一设备ID">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="editDeviceStatus">状态:</label>' +
            '<select id="editDeviceStatus" name="status">' +
            '<option value="true"' + (device.status === true ? ' selected' : '') + '>正常</option>' +
            '<option value="false"' + (device.status === false ? ' selected' : '') + '>关闭</option>' +
            '</select>' +
            '</div>' +
            '<div class="form-actions">' +
            '<button type="button" onclick="updateDevice()" style="background: #ffc107;">更新设备</button>' +
            '<button type="button" onclick="showDevices()" style="background: #6c757d; margin-left: 10px;">取消</button>' +
            '</div>' +
            '</form>' +
            '</div>';

        document.getElementById('contentArea').innerHTML = html;
    }

    // 更新设备
    async function updateDevice() {
        console.log(document.getElementById('editDeviceId').value);
        const id = document.getElementById('editDeviceId').value;
        const deviceName = document.getElementById('editDeviceName').value.trim();
        const deviceType = document.getElementById('editDeviceType').value;
        const deviceLocation = document.getElementById('editDeviceLocation').value.trim();
        const deviceId = document.getElementById('editDeviceDeviceId').value.trim();
        const deviceStatus = document.getElementById('editDeviceStatus').value === 'true';

        console.log('更新设备数据:', {
            id: id,
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        });

        // 前端验证
        if (!deviceName) {
            alert('设备名称不能为空！');
            return;
        }
        if (!deviceType) {
            alert('请选择设备类型！');
            return;
        }
        if (!deviceLocation) {
            alert('设备位置不能为空！');
            return;
        }

        const formData = {
            id: parseInt(id),
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        };

        axios.put(`/api/devices/update`, {
            id: parseInt(id),
            name: deviceName,
            type: deviceType,
            location: deviceLocation,
            deviceId: deviceId,
            status: deviceStatus
        }).then(async res => {
            alert('✅ 设备更新成功！');
            await showDevices(); // 返回设备列表
        }).catch(err => {
            console.error('更新设备错误:', err);
            alert('❌ 更新设备失败: ' + err.message);
        })
    }

    // 删除设备
    async function deleteDevice(id) {
        if (!confirm('确定要删除这个设备吗？此操作不可恢复！')) {
            return;
        }

        console.log('删除设备 ID:', id);

        axios.delete(`/api/devices/delete/` + (id))
            .then(res => {
                alert('✅ 设备删除成功！');
                showDevices(); // 刷新设备列表
            })
            .catch(error => {
                console.error('删除设备错误:', error);
                alert('❌ 删除设备失败: ' + error.message);
            });
    }

</script>
</body>
</html>